import 'dart:async';
import 'dart:io';
import 'dart:convert';
import 'package:flutter/material.dart';

class MyESPApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Socket Communication',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _message = '';

  @override
  void initState() {
    super.initState();

    // 每隔500毫秒连接一次ESP32
    Timer.periodic(Duration(milliseconds: 500), (timer) {
      _connectToESP32();
    });
  }

  void _connectToESP32() async {
    try {
      Socket socket = await Socket.connect('192.168.4.1', 80);
      print('Connected to: ${socket.remoteAddress.address}:${socket.remotePort}');

      socket.listen(
            (data) {
          String message = utf8.decode(data);
          print('Received data: $message');

          setState(() {
            _message = message; // 更新UI
          });
        },
        onError: (error) {
          print('Error: $error');
          socket.destroy();
        },
        onDone: () {
          print('Disconnected from server');
          socket.destroy();
        },
      );
    } catch (e) {
      print('Error: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("ESP32连接"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Message from ESP32:',
            ),
            Text(
              _message,
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
    );
  }
}